package com.jgc.interrupt;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2022/3/23.
 * 来自 大厂学院 juc
 */
public class InterruptDemo2 {
    public static void main(String[] args) {
//        m1();
//        m2();
        System.out.println(Thread.currentThread().getName() + "----" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + "----" + Thread.interrupted());
        System.out.println(11111);
        Thread.currentThread().interrupt();
        System.out.println(222222);
        System.out.println(Thread.currentThread().getName() + "----" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + "----" + Thread.interrupted());
    }

    private static void m2() {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("-----isInterrupted()==true,程序结束");
                    break;
                }
                /*try {
                    Thread.currentThread().join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    Thread.currentThread().wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {//打断异常之后，线程的中断标志清除。需要再次调用
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
                System.out.println("----hello interruped");
            }
        }, "t1");
        t1.start();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            t1.interrupt();
        },"t2").start();
    }

    private static void m1() {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.println("----------i=" + i);
            }
            System.out.println("t1.interrupt()调用之前,t1线程中断标志" + Thread.currentThread().isInterrupted());
        }, "t1");
        t1.start();
        System.out.println("t1.interrupt()调用之前,t1线程中断标志默认值01" + t1.isInterrupted());
        try {
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
        System.out.println("t1.interrupt()调用之后,t1线程中断标志02" + t1.isInterrupted());
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("t1.interrupt()调用之后,t1线程中断标志03" + t1.isInterrupted());
    }
}
